package com.ybw.rocketmq.demo.mq;

import com.alibaba.fastjson.JSON;
import com.ybw.rocketmq.demo.constant.MqConstant;
import com.ybw.rocketmq.demo.dto.OrderStep;
import com.ybw.rocketmq.demo.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * 生产者
 *
 * @author ybwei
 * @date 2022/3/8 21:08
 **/
@Component("sender")
@Slf4j
public class Sender {

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 顺序发送
     * 注：想要实现顺序消费，发送方式必须为同步发送，异步发送无法保证消息的发送顺序！
     *
     * @param orderStep
     * @return void
     * @throws
     * @methodName: syncSendOrderly
     * @author ybwei
     * @date 2022/3/8 19:52
     */
    public void syncSendOrderly(OrderStep orderStep) {
        Message<OrderStep> message = MessageBuilder.withPayload(orderStep)
                .setHeader(MessageConst.PROPERTY_KEYS, StringUtils.generateUUID())
                .setHeader(MessageConst.PROPERTY_PRODUCER_GROUP, MqConstant.PRODUCER_GROUP)
                .build();
        //hashKey:该参数的作用即是在发送消息的时候，固定发送到一个队列（默认情况下rocketmq中的topic有4个队列）以保证顺序。
        //基于 hashKey 的哈希值取余，选择对应的队列
        SendResult sendResult = rocketMQTemplate.syncSendOrderly(MqConstant.TOPIC, message, orderStep.getOrderId().toString());
        log.info("sendResult:{}", JSON.toJSONString(sendResult));
    }


}
